<template>
  <div>
    <van-nav-bar
      title="头像"
      right-text="确定"
      left-arrow
      @click-left="$emit('close')"
      @click-right="confirm"
    />
    <img class="img" :src="img" alt="" />
  </div>
</template>

<script>
import { editUserAvater } from '@/api/user'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
export default {
  name: 'AvaterPup',
  props: {
    img: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = document.querySelector('.img')
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move', // 画布可以拖动
      aspectRatio: 1, // 画框比例
      autoCropArea: 1,
      cropBoxMovable: false, // 画布移动
      cropBoxResizable: false
    })
  },
  methods: {
    confirm () {
      // this.cropper.getData()服务端调用的方法
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        const formData = new FormData()
        formData.append('photo', blob)
        try {
          const { data } = await editUserAvater(formData)
          console.log(data)
          this.$emit('editImg', data.photo)
        } catch (err) {
          console.log(err)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.img {
  display: block;
  width: 100%;
}
</style>
